import 'package:flutter/material.dart';
import 'package:wanandroid/common/common_index.dart';
import 'package:rxdart/rxdart.dart';

class SplashPage extends StatefulWidget {
  @override
  _SplashPageState createState() => _SplashPageState();
}

class _SplashPageState extends State<SplashPage> {
  TimerUtil _timerUtil;

  List<String> _guideList = [
    Utils.getImgPath('guide1'),
    Utils.getImgPath('guide2'),
    Utils.getImgPath('guide3'),
    Utils.getImgPath('guide4'),
  ];

  List<Widget> _bannerList = new List();

  int _status = 0;
  int _count = 3;

  SplashModel _splashModel;

  @override
  void initState() {
    super.initState();
    _loadSplashData();
    _initAsync();
  }

  void _loadSplashData() {
    HttpUtil httpUtil = new HttpUtil();
    httpUtil.getSplash().then((splashModel) async {
      await SpUtil.getInstance();
      _splashModel = SpHelper.getSplashModel();
      if (!ObjectUtil.isEmpty(splashModel.imgUrl)) {
        if (_splashModel == null ||
            (_splashModel.imgUrl != splashModel.imgUrl)) {
          SpUtil.putString(
              Constants.KEY_SPLASH_MODEL, json.encode(splashModel));
          setState(() {
            _splashModel = splashModel;
          });
        }
      } else {
        SpUtil.putString(Constants.KEY_SPLASH_MODEL, '');
      }
    });
  }

  void _initAsync() {
    Observable.just(1).delay(new Duration(milliseconds: 1000)).listen((_) {
      if (SpUtil.getBool(Constants.KEY_GUIDE) != true &&
          ObjectUtil.isNotEmpty(_guideList)) {
        SpUtil.putBool(Constants.KEY_GUIDE, true);
        _initBanner();
      } else {
        _initSplash();
      }
    });
  }

  void _initBanner() {
    _initBannerData();
    setState(() {
      _status = 2;
    });
  }

  void _initBannerData() {
    for (int i = 0, length = _guideList.length; i < length; i++) {
      if (i == length - 1) {
        _bannerList.add(Stack(
          children: <Widget>[
            Image.asset(_guideList[i],
                fit: BoxFit.fill,
                width: double.infinity,
                height: double.infinity),
            Align(
              alignment: Alignment.bottomCenter,
              child: Container(
                margin: EdgeInsets.only(bottom: 160),
                child: RaisedButton(
                  textColor: Colors.white,
                  color: Colors.indigoAccent,
                  child: Text(
                    '立即体验',
                    style: TextStyle(fontSize: 16.0),
                  ),
                  onPressed: () {
                    _goMain();
                  },
                ),
              ),
            ),
          ],
        ));
      } else {
        _bannerList.add(Image.asset(_guideList[i],
            fit: BoxFit.fill, width: double.infinity, height: double.infinity));
      }
    }
  }

  void _initSplash() {
    _splashModel = SpHelper.getSplashModel();
    if (_splashModel == null) {
      _goMain();
    } else {
      _doCountDown();
    }
  }

  void _doCountDown() {
    setState(() {
      _status = 1;
    });
    _timerUtil = new TimerUtil(mTotalTime: 3 * 1000);
    _timerUtil.setOnTimerTickCallback((int tick) {
      double _tick = tick / 1000;
      setState(() {
        _count = _tick.toInt();
      });
      if (_tick == 0) {
        _goMain();
      }
    });
    _timerUtil.startCountDown();
  }

  void _goMain() {
    Navigator.of(context).pushReplacementNamed('/MainPage');
  }

  Widget _buildSplashBg() {
    return Image.asset(
      Utils.getImgPath('splash_bg'),
      fit: BoxFit.fill,
      width: double.infinity,
      height: double.infinity,
    );
  }

  Widget _buildAdsWidget() {
    if (_splashModel == null) {
      return Container(
        height: 0.0,
      );
    }
    return Offstage(
      offstage: !(_status == 1),
      child: InkWell(
        onTap: () {
          if (ObjectUtil.isEmpty(_splashModel.url)) return;
          _goMain();
          NavigatorUtil.pushWeb(context,
              title: _splashModel.title, url: _splashModel.url);
        },
        child: Container(
            alignment: Alignment.center,
            child: CachedNetworkImage(
              imageUrl: _splashModel.imgUrl,
              width: double.infinity,
              height: double.infinity,
              fit: BoxFit.fill,
              placeholder: _buildSplashBg(),
              errorWidget: _buildSplashBg(),
            )),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Material(
      child: Stack(
        children: <Widget>[
          Offstage(
            offstage: !(_status == 0),
            child: _buildSplashBg(),
          ),
          Offstage(
              offstage: !(_status == 2),
              child: ObjectUtil.isEmpty(_bannerList)
                  ? Container(
                      color: Colors.pink,
                    )
                  : Swiper(
                      autoStart: false,
                      circular: false,
                      indicator: CircleSwiperIndicator(
                        radius: 4.0,
                        padding: EdgeInsets.only(bottom: 30.0),
                        itemColor: Colors.black26,
                      ),
                      children: _bannerList)),
          _buildAdsWidget(),
          Offstage(
            offstage: !(_status == 1),
            child: Container(
              alignment: Alignment.bottomRight,
              margin: EdgeInsets.all(20.0),
              child: InkWell(
                onTap: () {
                  _goMain();
                },
                child: Container(
                  padding: EdgeInsets.all(12.0),
                  child: Text(
                    '跳过 $_count',
                    style: TextStyle(fontSize: 14.0, color: Colors.white),
                  ),
                  decoration: BoxDecoration(
                      color: Color(0x66000000),
                      borderRadius: BorderRadius.all(Radius.circular(5.0)),
                      border: Border.all(width: 0.33, color: ColorT.divider)),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}
